<?php
declare (strict_types=1);

namespace app\common\queue\bokecc;

use app\common\library\Queue;
use app\course\logic\live\admin\LiveSectionSyncLogs;
use app\course\logic\live\BokeKT;
use app\course\model\live\admin\CourseSectionLive;
use think\facade\Env;
use think\facade\Request;

class YKTViewRecord
{
    public function run()
    {
        $data = Request::post();
        // 直播ID
        $liveId = $data['live_id'];
        // 直播间ID
        $roomId = $data['room_id'];
        // 记录
        $logObj = new LiveSectionSyncLogs();
        // 是否同步过记录
        $isSynced = $logObj->isSynced($roomId, $liveId);
        if ($isSynced) return;

        // 根据直播间ID获取
        $section         = (new CourseSectionLive)->where('cc_room_id', $roomId)->field(['room_no', 'course_id'])->findOrEmpty();
        $courseSectionId = $section->getAttr('room_no');
        $courseId        = $section->getAttr('course_id');
        if (!$courseId || !$courseSectionId) return;

        // 调用接口获取
        $response = $this->getStatis($roomId, $liveId);
        $count    = $this->updatedOrCreated($courseId, $courseSectionId, $response->data);
        if (Env::get('app_debug')) {
            echo '同步云课堂直播间【' . $roomId . '】,直播ID为【' . $liveId . '】的观看时，共计【' . $count . '】条数据';
        }

        $log = [
            'room_id'           => $roomId,
            'live_id'           => $liveId,
            'total_count'       => $count,
            'success_count'     => $count,
            'course_id'         => $courseId,
            'course_section_id' => $courseSectionId
        ];
        // 更新同步记录数
        $logObj->updateOrCreatedLog($log);

    }

    protected function getStatis($roomId, $liveId)
    {
        $cc = new BokeKT();
        return $cc->record($roomId, $liveId);
    }

    /**
     * 创建直播观看记录
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/11
     *
     * @static
     * @param int   $courseId
     * @param int   $courseSectionId
     * @param array $datas
     * @return int
     */
    protected function updatedOrCreated(int $courseId, int $courseSectionId, array $datas): int
    {
        $count = 0;
        foreach ($datas as $data) {
            // 计算观看直播时长
            $enterTime = strtotime($data->enter_time);
            $exitTime  = strtotime($data->exit_time);
            $watchTime = $exitTime - $enterTime;
            $userId    = $data->viewerid;
            // 是否为本地系统用户ID
            if (is_numeric($userId)) {
                // 推送学习记录处理任务队列
                Queue::push('LearnRecord', [
                    'course_id'  => $courseId,
                    'section_id' => $courseSectionId,
                    'mid'        => $userId,
                    'watch_time' => $watchTime
                ]);
                $count++;
            }
        }

        return $count;
    }
}